<?php
// +----------------------------------------------------------------------
// | Desc: [ Better-充值审核 ]
// +----------------------------------------------------------------------
// | Author: huangzhen_20210406
// +----------------------------------------------------------------------

namespace app\common\model;
use think\facade\Db;
use app\api\controller\Index;

class CardsTransCredit extends Common
{
    //---------------------------------------------后端---------------------------------------------------------------
    /**
     * 返回layui的table所需要的格式
     * @param $post
     * @param $user_id
     * @return mixed
     * @throws \think\db\exception\DbException
     */
    public function tableDataAdmin($post)
    {
        $list_rows  = $post['limit'] ?? config('paginate.list_rows');
        $page       = $post['page'] ?? config('paginate.page');

        $where =[];
        if(isset($post['user_name']) && !empty($post['user_name'])){
            $where[] = ['username', '=', trim($post['user_name'])];
        }
        if(isset($post['card_num']) && !empty($post['card_num'])){
            $where[] = ['ct.card_num', '=', trim($post['card_num'])];
        }
        if(isset($post['idMatchNumber']) && !empty($post['idMatchNumber'])){
            $where[] = ['ct.idMatchNumber', '=', trim($post['idMatchNumber'])];
        }
        if(isset($post['shopping']) && !empty($post['shopping'])){
            $where[] = ['ct.shopping', 'like', '%' . trim($post['shopping']) . '%'];
        }
        if(isset($post['credit_status']) && strlen($post['credit_status'])>0){
            $where[] = ['ct.credit_status', '=', trim($post['credit_status'])];
        }
        if(isset($post['datetime']) && !empty($post['datetime'])){
            $time_list = explode(' _ ' , $post['datetime']);
            $start_time = $time_list[0] . " 00:00:00";
            $end_time   = $time_list[1] . " 23:59:59";
            $where[] = ['ct.ctime', 'between', "{$start_time},{$end_time}"];
        }

        $list = Db::name('cards_trans_credit')->alias('ct')
            ->leftJoin('user u' , 'u.id=ct.user_id')
            ->field('u.username,ct.*')
            ->order('ct.ctime desc')
            ->where($where)
            ->paginate(['list_rows' => $list_rows, 'page' => $page])
            ->toArray();
        return $result = [
            'code'  => 0,
            'msg'   => lang('get info success'),
            'data'  => $list['data'],
            'count' => $list['total'],
        ];
    }

    public static function setCreditAmount($credit_id,$manage_id)
    {
        $list = Db::name('cards_trans_credit')->where(['id' => $credit_id , 'credit_status' => 0])->find();
        $blog = false;
        if (!empty($list)) {
            $blog = self::endCredit([
                'card_num'      =>  $list['card_num'],
                'user_id'       =>  $list['user_id'],
                'credit_amount' =>  $list['amount'],
                'shopping'      =>  $list['shopping'],
                'credit_id'     =>  $credit_id,
                'manage_id'     =>  $manage_id
            ]);
        }
        return $blog;
    }

    public static function endCredit($data,$is_update=1)
    {
        $time       = getUtcTime();
        $blog       = false;

        $card_num       = $data['card_num'];
        $user_id        = $data['user_id'];
        $credit_amount  = $data['credit_amount'];
        $shopping       = $data['shopping'];
        $credit_id      = $data['credit_id'] ?? '';
        $manage_id      = $data['manage_id'] ?? 0;

        $card_num4      = substr($card_num , -4);
        $card_num6      = substr($card_num , 0 , 6);

        $user_list      = Db::name('user')->where(['id' => $user_id])->find();
        $user_balance   = $user_list['balance'];
        $username       = $user_list['username'];

        $card_list      = Db::name('cards')->where(['card_num' => $card_num])->find();
        $bank_type      = $card_list['bank_type'];
        $card_type      = $card_list['card_type'];
        $refund_amount  = $card_list['refund_amount'];

        Db::startTrans();
        try {
            //第一步 账户余额+退款金额
            //is_update == 1 , 要把退款加入到用户余额,
            //is_update == 2 , 退款退到卡上了，不需要重复退到用户余额 包含 银行12（556766） ,银3,
            if($is_update == 1 ){
                $end_user_balance = $user_balance + $credit_amount;
                Db::name('user_cash_log')->save([
                    'user_id' => $user_id,
                    'type' => 0,
                    'action_type' => 4,
                    'amount' => $credit_amount,
                    'balance' => $end_user_balance,
                    'desc' => "Refund From '{$shopping}' With Card({$card_num6} **** {$card_num4})",
                    'ctime' => $time
                ]);
            }else{
                $end_user_balance = $user_balance;
            }
            //第二步 扣除退款手续费
            $credit_server_set = UserSet::getCardSet($user_id);
            $credit_server_set_rate = $credit_server_set[$bank_type][$card_type]['rate_refund'] ?? 0.05;
            $credit_server_amount = getSprintf(round($credit_amount * $credit_server_set_rate,2));
            $end_user_balance -= $credit_server_amount;
            Db::name('user_cash_log')->save([
                'user_id' => $user_id,
                'type' => 1,
                'action_type' => 5,
                'amount' => $credit_server_amount,
                'balance' => $end_user_balance,
                'desc' => "退款服务费 ({$card_num6} **** {$card_num4})",
                'ctime' => $time+1
            ]);
            //记录卡的退款服务费
            $refund_amount += $credit_server_amount; //累加卡的退款服务费
            Db::name('cards')->where(['card_num'=>$card_num])->update(['refund_amount'=>$refund_amount]);
            //第三步更新最新卡余额
            Db::name('user')->where(['id' => $user_id])
                ->update(['balance' => $end_user_balance]);
            //更新退款日志
            if($is_update == 1 ){
                if(!empty($credit_id)){
                    Db::name('cards_trans_credit')->where(['id' => $credit_id])
                        ->update([
                            'credit_status' => 1,
                            'utime' => $time,
                            'server_amount' => $credit_server_amount
                        ]);
                }
            }
            //记录操作日志
            ManageLog::saveManageLog([
                'manage_id' => $manage_id,
                'desc'      => 'credit_amount_' . $card_type,
                'time'      => $time,
                'content'   => json_encode([
                    'username'      => $username,
                    'card_num'      => $card_num,
                    'credit_amount' => $credit_amount
                ])
            ]);
            $blog = true;
            Db::commit();
        } catch (\Exception $e) {
            var_dump($e->getMessage() . '---' . $e->getLine());
            Db::rollback();
        }
        return $blog;
    }

    public static function changeCredit($data , $manage_id)
    {
        $id_array   = $data['id_array'];
        $success_num =0;
        foreach ($id_array as $v){
            $credit_id   = $v;
            $re = self::setCreditAmount($credit_id , $manage_id);
            if($re){
                $success_num++;
            }else{
                continue;
            }
        }
        return $success_num;
    }

    public static function getCardSet($user_id)
    {
        $list = Db::name('user_set')->where(['user_id' => $user_id])
            ->order('type')->find();
        if(empty($list)){
            $type  = Db::name('user')->where(['id' => $user_id])->value('grade');
            //grade = 2时候，事管理员认证用户， 那么user_set 中type=1就按用户认证状态算
            if($type == 2){
                $type =1;
            }
            $list = Db::name('user_set')->where(['type' => $type , 'user_id'=>0])->find();
        }
        return $list;
    }
}